package com.lingshi.shopping_admin_service.service;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lingshi.shopping_admin_service.mapper.RoleMapper;
import com.lingshi.shopping_admin_service.mapper.RolePermissionMapper;
import com.lingshi.shopping_common.entity.AdminRole;
import com.lingshi.shopping_common.entity.Role;
import com.lingshi.shopping_common.entity.RolePermission;
import com.lingshi.shopping_common.service.IRoleService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@DubboService
@Transactional
public class RoleServiceImpl implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Override
    public void add(Role role) {
        roleMapper.insert(role);
    }

    @Override
    public void update(Role role) {
        roleMapper.updateById(role);
    }

    @Override
    public void delete(Long rid) {
        roleMapper.deleteById(rid);

        LambdaUpdateWrapper<RolePermission> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(RolePermission::getRid,rid);
        rolePermissionMapper.delete(updateWrapper);
    }

    @Override
    public Role findById(Long rid) {
        return roleMapper.findById(rid);
    }

    @Override
    public List<Role> findAll() {
        return roleMapper.selectList(null);
    }

    @Override
    public Page<Role> search(int page, int size) {
        return roleMapper.selectPage(new Page<>(page,size),null);
    }

    @Override
    public void updatePermissionToRole(Long rid, Long[] pids) {
        //先删除角色权限表所有数据
        LambdaUpdateWrapper<RolePermission> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(RolePermission::getRid, rid);
        rolePermissionMapper.delete(updateWrapper);
        //再添加新的权限
        for (Long pid : pids) {
            RolePermission rolePermission = new RolePermission();
            rolePermission.setPid(pid);
            rolePermission.setRid(rid);
            rolePermissionMapper.insert(rolePermission);
        }
    }
}
